package lgq.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lgq.service.CourseManager;
import lgq.service.TeacherManager;
import model.Course;
import model.Teacher;
import util.Page;

public class FindTeacherServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*try{
	    Page<Teacher> p=(Page<Teacher>) request.getSession().getAttribute("page");
		}catch(Exception e)
		{
			System.out.println("不是teacher的page");
			request.getSession().setAttribute("serchtype",null);
			request.getSession().setAttribute("keycode",null);
		}finally{
			System.out.println("进入servlet");
		}*/
		int pageNo=1;
		int pageSize=10;
		String keycode="";
		
		if (null != request.getParameter("serchtype")) {
			request.getSession().setAttribute("serchtype",request.getParameter("serchtype"));
		}
		
		if (null != request.getParameter("keycode")) {
			request.getSession().setAttribute("keycode",request.getParameter("keycode"));
			keycode = request.getParameter("keycode");
		} else {
			keycode = (String) request.getSession().getAttribute("keycode");
		}
		try{
			if(request.getParameter("pageNo")!=null)
			{
				pageNo=Integer.parseInt(request.getParameter("pageNo"));
			}
			if(request.getParameter("pageSize")!=null)
			{
				pageSize=Integer.parseInt(request.getParameter("pageSize"));
				
				request.getSession().setAttribute("pageSize", pageSize);
			}
			if(request.getSession().getAttribute("pageSize")!=null)
			{
				pageSize=(Integer) request.getSession().getAttribute("pageSize");
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		Page<Teacher> page=null;
		if("teachername".equals(request.getSession().getAttribute("serchtype")))
		{
			page=new TeacherManager().getByName(pageNo, pageSize,keycode);				
		}
		else if("teacherid".equals(request.getSession().getAttribute("serchtype")))
		{
			try{
			Page<Teacher> p=new Page<Teacher>(1, 1);
			List<Teacher> list=new ArrayList<Teacher>();
			if(null!=new TeacherManager().getById(Integer.parseInt(keycode)))
			{
				list.add(new TeacherManager().getById(Integer.parseInt(keycode)));
				p.setList(list);
				p.setTotalCount(1);
			}					
			page=p;
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{			
			page=new TeacherManager().getAllTeacher(pageNo, pageSize);
		}
		request.setAttribute("page", page);
		request.getRequestDispatcher("/Train/TeacherManager.jsp").forward(request, response);
	}
	
}
